{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dealing with JSON\n",
    "\n",
    "By [Allison Parrish](http://www.decontextualize.com/)\n",
    "\n",
    "JSON (JavaScript Object Notation) is a popular way of formatting data so that it can be shared between different computer systems. The idea is that you might have a data structure in one application, and you want to be able to send that data structure to another application. In order to do this, we need three things: (1) a common format that both applications understand (like JSON); (2) a way to take an in-memory data structure on the source machine and convert it to that format---this is called \"serialization\"; and (3) a way to change the \"serialized\" data back into an in-memory data structure on the target machine.\n",
    "\n",
    "Python has a library called `json` that does the work in (2) and (3) for us. The json library has two important functions: `dumps` (\"dump string\"), which converts a Python data structure to JSON, and `loads` (\"load string\") which converts a JSON string to a Python data structure. Here's an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "str"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mouse = {\"name\": \"gerald\", \"length\": 22.5, \"favorite_food\": \"gouda\", \"age\": 2}\n",
    "mouse_json = json.dumps(mouse)\n",
    "type(mouse_json)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'{\"name\": \"gerald\", \"length\": 22.5, \"favorite_food\": \"gouda\", \"age\": 2}'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mouse_json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see, the literal notation for Python objects (i.e., the way we write them in our programs) has a strong resemblance to the way that same data looks when encoded as JSON. There are a number of differences (i.e., JSON uses null instead of None; JSON always has double-quoted keys and values; escape sequences in JSON strings are very different from those in Python), but for the most part the formatted data should look very familiar. The json library can take pretty much any Python data structure and turn it into JSON---dictionaries, lists, ints, floats---even nested data structures, like dictionaries with lists as values.\n",
    "\n",
    "The great thing about JSON (as illustrated above) is that JSON-encoded data is just a string. I could copy this JSON data into an e-mail and send it to you, without having to worry about formatting, and you could paste it back into Python to get back the original data structure. (Or I could make a web application that encodes data structures as JSON, and you could read them with another computer program.)\n",
    "\n",
    "## JSON data from Corpora project\n",
    "\n",
    "JSON data is often made available as files with a `.json` extension. You can download these files and use them in your program. One good source of fun data in JSON format is Darius Kazemi's [Corpora project](https://github.com/dariusk/corpora/), which makes available an eclectic collection of \"static corpora (plural of 'corpus') that are potentially useful in the creation of weird internet stuff.\" For example, there's [a list of common English nouns](https://github.com/dariusk/corpora/blob/master/data/words/nouns.json), [a list of color names with corresponding RGB values](https://github.com/dariusk/corpora/blob/master/data/colors/xkcd.json), and even [a list of guitar manufacturers](https://github.com/dariusk/corpora/blob/master/data/music/a_list_of_guitar_manufacturers.json).\n",
    "\n",
    "These files are great sources for making experimental generative text projects. The simplest way to use one in your notebook is to download it from Github and put it in the same directory as your notebook file. To download one of the files, navigate to it in the repository (click on the `data` directory and navigate through the categories until you find something that looks interesting), then click on the button that reads \"Raw.\" This will show the JSON data directly in your browser, without the surrounding formatting of the Github web page. Then use your browser to save the file (usually `File > Save Page As...`). Save the file in the same directory as your notebook. You should see it pop up in Jupyter Notebook's `Home` tab.\n",
    "\n",
    "### Random zoos\n",
    "\n",
    "As a quick example, I'm going to make a random zoo with [this list of common animals](https://github.com/dariusk/corpora/blob/master/data/animals/common.json). I've already downloaded this file as `common.json` in the same directory as this notebook. To \"deserialize\" it into a Python data structure, I'll use the `open()` function and the `loads()` function from the `json` library like so:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "animal_data = json.loads(open(\"common.json\").read())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here's what the resulting data structure looks like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'animals': ['aardvark',\n",
       "  'alligator',\n",
       "  'alpaca',\n",
       "  'antelope',\n",
       "  'ape',\n",
       "  'armadillo',\n",
       "  'baboon',\n",
       "  'badger',\n",
       "  'bat',\n",
       "  'bear',\n",
       "  'beaver',\n",
       "  'bison',\n",
       "  'boar',\n",
       "  'buffalo',\n",
       "  'bull',\n",
       "  'camel',\n",
       "  'canary',\n",
       "  'capybara',\n",
       "  'cat',\n",
       "  'chameleon',\n",
       "  'cheetah',\n",
       "  'chimpanzee',\n",
       "  'chinchilla',\n",
       "  'chipmunk',\n",
       "  'cougar',\n",
       "  'cow',\n",
       "  'coyote',\n",
       "  'crocodile',\n",
       "  'crow',\n",
       "  'deer',\n",
       "  'dingo',\n",
       "  'dog',\n",
       "  'donkey',\n",
       "  'dromedary',\n",
       "  'elephant',\n",
       "  'elk',\n",
       "  'ewe',\n",
       "  'ferret',\n",
       "  'finch',\n",
       "  'fish',\n",
       "  'fox',\n",
       "  'frog',\n",
       "  'gazelle',\n",
       "  'gila monster',\n",
       "  'giraffe',\n",
       "  'gnu',\n",
       "  'goat',\n",
       "  'gopher',\n",
       "  'gorilla',\n",
       "  'grizzly bear',\n",
       "  'ground hog',\n",
       "  'guinea pig',\n",
       "  'hamster',\n",
       "  'hedgehog',\n",
       "  'hippopotamus',\n",
       "  'hog',\n",
       "  'horse',\n",
       "  'hyena',\n",
       "  'ibex',\n",
       "  'iguana',\n",
       "  'impala',\n",
       "  'jackal',\n",
       "  'jaguar',\n",
       "  'kangaroo',\n",
       "  'koala',\n",
       "  'lamb',\n",
       "  'lemur',\n",
       "  'leopard',\n",
       "  'lion',\n",
       "  'lizard',\n",
       "  'llama',\n",
       "  'lynx',\n",
       "  'mandrill',\n",
       "  'marmoset',\n",
       "  'mink',\n",
       "  'mole',\n",
       "  'mongoose',\n",
       "  'monkey',\n",
       "  'moose',\n",
       "  'mountain goat',\n",
       "  'mouse',\n",
       "  'mule',\n",
       "  'muskrat',\n",
       "  'mustang',\n",
       "  'mynah bird',\n",
       "  'newt',\n",
       "  'ocelot',\n",
       "  'opossum',\n",
       "  'orangutan',\n",
       "  'oryx',\n",
       "  'otter',\n",
       "  'ox',\n",
       "  'panda',\n",
       "  'panther',\n",
       "  'parakeet',\n",
       "  'parrot',\n",
       "  'pig',\n",
       "  'platypus',\n",
       "  'polar bear',\n",
       "  'porcupine',\n",
       "  'porpoise',\n",
       "  'prairie dog',\n",
       "  'puma',\n",
       "  'rabbit',\n",
       "  'raccoon',\n",
       "  'ram',\n",
       "  'rat',\n",
       "  'reindeer',\n",
       "  'reptile',\n",
       "  'rhinoceros',\n",
       "  'salamander',\n",
       "  'seal',\n",
       "  'sheep',\n",
       "  'shrew',\n",
       "  'silver fox',\n",
       "  'skunk',\n",
       "  'sloth',\n",
       "  'snake',\n",
       "  'squirrel',\n",
       "  'tapir',\n",
       "  'tiger',\n",
       "  'toad',\n",
       "  'turtle',\n",
       "  'walrus',\n",
       "  'warthog',\n",
       "  'weasel',\n",
       "  'whale',\n",
       "  'wildcat',\n",
       "  'wolf',\n",
       "  'wolverine',\n",
       "  'wombat',\n",
       "  'woodchuck',\n",
       "  'yak',\n",
       "  'zebra']}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "animal_data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Something to know about the Corpora Project (and a lot of JSON data in general, really) is that there's *no standard way* of arranging the data. In order to work with this data, you'll have to look at the data structure and figure out how to write expressions that access the data you want. In this case, the `animal_data` value is a dictionary:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(animal_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That dictionary has a single key, `animals`, whose value is a list of strings:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['aardvark',\n",
       " 'alligator',\n",
       " 'alpaca',\n",
       " 'antelope',\n",
       " 'ape',\n",
       " 'armadillo',\n",
       " 'baboon',\n",
       " 'badger',\n",
       " 'bat',\n",
       " 'bear',\n",
       " 'beaver',\n",
       " 'bison',\n",
       " 'boar',\n",
       " 'buffalo',\n",
       " 'bull',\n",
       " 'camel',\n",
       " 'canary',\n",
       " 'capybara',\n",
       " 'cat',\n",
       " 'chameleon',\n",
       " 'cheetah',\n",
       " 'chimpanzee',\n",
       " 'chinchilla',\n",
       " 'chipmunk',\n",
       " 'cougar',\n",
       " 'cow',\n",
       " 'coyote',\n",
       " 'crocodile',\n",
       " 'crow',\n",
       " 'deer',\n",
       " 'dingo',\n",
       " 'dog',\n",
       " 'donkey',\n",
       " 'dromedary',\n",
       " 'elephant',\n",
       " 'elk',\n",
       " 'ewe',\n",
       " 'ferret',\n",
       " 'finch',\n",
       " 'fish',\n",
       " 'fox',\n",
       " 'frog',\n",
       " 'gazelle',\n",
       " 'gila monster',\n",
       " 'giraffe',\n",
       " 'gnu',\n",
       " 'goat',\n",
       " 'gopher',\n",
       " 'gorilla',\n",
       " 'grizzly bear',\n",
       " 'ground hog',\n",
       " 'guinea pig',\n",
       " 'hamster',\n",
       " 'hedgehog',\n",
       " 'hippopotamus',\n",
       " 'hog',\n",
       " 'horse',\n",
       " 'hyena',\n",
       " 'ibex',\n",
       " 'iguana',\n",
       " 'impala',\n",
       " 'jackal',\n",
       " 'jaguar',\n",
       " 'kangaroo',\n",
       " 'koala',\n",
       " 'lamb',\n",
       " 'lemur',\n",
       " 'leopard',\n",
       " 'lion',\n",
       " 'lizard',\n",
       " 'llama',\n",
       " 'lynx',\n",
       " 'mandrill',\n",
       " 'marmoset',\n",
       " 'mink',\n",
       " 'mole',\n",
       " 'mongoose',\n",
       " 'monkey',\n",
       " 'moose',\n",
       " 'mountain goat',\n",
       " 'mouse',\n",
       " 'mule',\n",
       " 'muskrat',\n",
       " 'mustang',\n",
       " 'mynah bird',\n",
       " 'newt',\n",
       " 'ocelot',\n",
       " 'opossum',\n",
       " 'orangutan',\n",
       " 'oryx',\n",
       " 'otter',\n",
       " 'ox',\n",
       " 'panda',\n",
       " 'panther',\n",
       " 'parakeet',\n",
       " 'parrot',\n",
       " 'pig',\n",
       " 'platypus',\n",
       " 'polar bear',\n",
       " 'porcupine',\n",
       " 'porpoise',\n",
       " 'prairie dog',\n",
       " 'puma',\n",
       " 'rabbit',\n",
       " 'raccoon',\n",
       " 'ram',\n",
       " 'rat',\n",
       " 'reindeer',\n",
       " 'reptile',\n",
       " 'rhinoceros',\n",
       " 'salamander',\n",
       " 'seal',\n",
       " 'sheep',\n",
       " 'shrew',\n",
       " 'silver fox',\n",
       " 'skunk',\n",
       " 'sloth',\n",
       " 'snake',\n",
       " 'squirrel',\n",
       " 'tapir',\n",
       " 'tiger',\n",
       " 'toad',\n",
       " 'turtle',\n",
       " 'walrus',\n",
       " 'warthog',\n",
       " 'weasel',\n",
       " 'whale',\n",
       " 'wildcat',\n",
       " 'wolf',\n",
       " 'wolverine',\n",
       " 'wombat',\n",
       " 'woodchuck',\n",
       " 'yak',\n",
       " 'zebra']"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "animal_data['animals']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "I'm just going to assign that list to a separate variable, so it's a little easier to work with:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "animals = animal_data['animals']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we'll make a zoo by selecting a random subset of these animals:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "In my zoo, we have the following kinds of animals:\n",
      "* zebra\n",
      "* boar\n",
      "* orangutan\n",
      "* elephant\n",
      "* mustang\n",
      "* salamander\n",
      "* chinchilla\n",
      "* mouse\n",
      "* dingo\n",
      "* woodchuck\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "my_zoo = random.sample(animals, 10)\n",
    "print(\"In my zoo, we have the following kinds of animals:\")\n",
    "for item in my_zoo:\n",
    "    print(\"* \" + item)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's add some personality to our zoo using [this list of moods](https://github.com/dariusk/corpora/blob/master/data/humans/moods.json). After having downloaded the raw JSON, you can grab the list of moods from the file like so:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "mood_data = json.loads(open(\"moods.json\").read())\n",
    "moods = mood_data[\"moods\"] # I had to look at the JSON data itself to determine that this was the correct key!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's generate a new text combining the two:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Current zoo report\n",
      "------------------\n",
      "The pig is invisible\n",
      "The silver fox is content\n",
      "The guinea pig is cynical\n",
      "The sloth is lousy\n",
      "The dog is defensive\n",
      "The koala is impatient\n",
      "The moose is appreciative\n",
      "The reindeer is depressed\n",
      "The lizard is replaced\n",
      "The dingo is reverent\n"
     ]
    }
   ],
   "source": [
    "print(\"Current zoo report\")\n",
    "print(\"------------------\")\n",
    "for i in range(10):\n",
    "    print(\"The \" + random.choice(animals) + \" is \" + random.choice(moods))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### More sophisticated data structures\n",
    "\n",
    "Not all JSON files have the same structure. Some of the files in the Corpora Project in particular aren't just dictionaries that have a list of strings. Let's say that we want to write tiny random narratives about the rivers of the world. Start with [this list of rivers](https://github.com/dariusk/corpora/blob/master/data/geography/rivers.json). You might want to just be able to grab one at random, but doing so will be a bit more complicated than what we did above because of the way the data is structured. Here's what the data looks like:\n",
    "\n",
    "    {\n",
    "      \"description\": \"A list of rivers.\",\n",
    "      \"source\": \"http://en.wikipedia.org/wiki/List_of_rivers_by_length\",\n",
    "      \"rivers\": [\n",
    "        {\n",
    "          \"name\": \"Nile\",\n",
    "          \"confluences\": [\"Kagera\"],\n",
    "          \"outflow\": \"Mediterranean\"\n",
    "        },\n",
    "        {\n",
    "          \"name\": \"Kagera\",\n",
    "          \"confluences\": [\"Nile\"],\n",
    "          \"outflow\": \"Mediterranean\"\n",
    "        },\n",
    "        {\n",
    "          \"name\": \"Amazon\",\n",
    "          \"confluences\": [\"Ucayali\",\"Apurímac\"],\n",
    "          \"outflow\": \"Atlantic Ocean\"\n",
    "        },\n",
    "        [...many more entries...]\n",
    "      ]\n",
    "    }\n",
    "    \n",
    "Take a look at this data and try to characterize how it's structured. The entire thing is a dictionary; there's a `description` key and a `source` key which aren't of tremendous interest to us. The value for the `rivers` key is where most of the useful information resides, so let's take a look at that value: it's a list! And each element of the list is *itself* a dictionary. Let's load the data and put our theory to the test:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "list"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "river_data = json.loads(open(\"rivers.json\").read())\n",
    "rivers = river_data[\"rivers\"]\n",
    "type(rivers)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Okay, so we have the list of rivers. Here's the first in the list (which we can take to be, hopefully, representative of the rest of the items in the list):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'confluences': ['Kagera'], 'name': 'Nile', 'outflow': 'Mediterranean'}"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rivers[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get the `name` key for this river dictionary:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Nile'"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rivers[0]['name']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get a list of *just* the river names, write a list comprehension that grabs just the `name` key of each dictionary in the list:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "river_names = [item['name'] for item in rivers]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Nile',\n",
       " 'Kagera',\n",
       " 'Amazon',\n",
       " 'Ucayali',\n",
       " 'Apurímac',\n",
       " 'Yangtze',\n",
       " 'Mississippi',\n",
       " 'Missouri',\n",
       " 'Jefferson',\n",
       " 'Yenisei',\n",
       " 'Angara',\n",
       " 'Selenge',\n",
       " 'Huang He',\n",
       " 'Ob',\n",
       " 'Irtysh',\n",
       " 'Paraná',\n",
       " 'Río de la Plata',\n",
       " 'Congo',\n",
       " 'Chambeshi',\n",
       " 'Amur',\n",
       " 'Argun',\n",
       " 'Lena',\n",
       " 'Mekong',\n",
       " 'Mackenzie',\n",
       " 'Slave',\n",
       " 'Peace',\n",
       " 'Finlay',\n",
       " 'Niger',\n",
       " 'Murray',\n",
       " 'Darling',\n",
       " 'Tocantins',\n",
       " 'Araguaia',\n",
       " 'Volga',\n",
       " 'Shatt al-Arab',\n",
       " 'Euphrates',\n",
       " 'Madeira',\n",
       " 'Mamoré',\n",
       " 'Grande',\n",
       " 'Caine',\n",
       " 'Rocha',\n",
       " 'Purús',\n",
       " 'Yukon',\n",
       " 'Indus',\n",
       " 'São Francisco',\n",
       " 'Syr Darya',\n",
       " 'Naryn',\n",
       " 'Salween',\n",
       " 'Saint Lawrence',\n",
       " 'Niagara',\n",
       " 'Detroit',\n",
       " 'Saint Clair',\n",
       " 'Saint Marys',\n",
       " 'Saint Louis',\n",
       " 'Rio Grande',\n",
       " 'Lower Tunguska',\n",
       " 'Brahmaputra',\n",
       " 'Tsangpo',\n",
       " 'Danube',\n",
       " 'Breg',\n",
       " 'Zambezi',\n",
       " 'Vilyuy',\n",
       " 'Araguaia',\n",
       " 'Ganges',\n",
       " 'Hooghly',\n",
       " 'Padma',\n",
       " 'Amu Darya',\n",
       " 'Panj',\n",
       " 'Japurá',\n",
       " 'Nelson',\n",
       " 'Saskatchewan',\n",
       " 'Paraguay',\n",
       " 'Kolyma',\n",
       " 'Pilcomayo',\n",
       " 'Upper Ob',\n",
       " 'Katun',\n",
       " 'Ishim',\n",
       " 'Juruá',\n",
       " 'Ural',\n",
       " 'Arkansas',\n",
       " 'Colorado',\n",
       " 'Olenyok',\n",
       " 'Dnieper',\n",
       " 'Aldan',\n",
       " 'Ubangi',\n",
       " 'Uele',\n",
       " 'Negro',\n",
       " 'Columbia',\n",
       " 'Pearl',\n",
       " 'Zhu Jiang',\n",
       " 'Red',\n",
       " 'Ayeyarwady',\n",
       " 'Kasai',\n",
       " 'Ohio',\n",
       " 'Allegheny',\n",
       " 'Orinoco',\n",
       " 'Tarim',\n",
       " 'Xingu',\n",
       " 'Orange',\n",
       " 'Northern Salado',\n",
       " 'Vitim',\n",
       " 'Tigris',\n",
       " 'Songhua',\n",
       " 'Tapajós',\n",
       " 'Don',\n",
       " 'Stony Tunguska',\n",
       " 'Pechora',\n",
       " 'Kama',\n",
       " 'Limpopo',\n",
       " 'Guaporé',\n",
       " 'Indigirka',\n",
       " 'Snake',\n",
       " 'Senegal',\n",
       " 'Uruguay',\n",
       " 'Murrumbidgee',\n",
       " 'Blue Nile',\n",
       " 'Churchill',\n",
       " 'Khatanga',\n",
       " 'Okavango',\n",
       " 'Volta',\n",
       " 'Beni',\n",
       " 'Platte',\n",
       " 'Tobol',\n",
       " 'Jubba',\n",
       " 'Shebelle',\n",
       " 'Içá',\n",
       " 'Magdalena',\n",
       " 'Han',\n",
       " 'Oka',\n",
       " 'Pecos',\n",
       " 'Upper Yenisei',\n",
       " 'Little Yenisei',\n",
       " 'Godavari',\n",
       " 'Guapay',\n",
       " 'Belaya',\n",
       " 'Cooper',\n",
       " 'Barcoo',\n",
       " 'Marañón',\n",
       " 'Dniester',\n",
       " 'Benue',\n",
       " 'Ili',\n",
       " 'Warburton',\n",
       " 'Georgina',\n",
       " 'Sutlej',\n",
       " 'Yamuna',\n",
       " 'Vyatka',\n",
       " 'Fraser',\n",
       " 'Mtkvari',\n",
       " 'Grande',\n",
       " 'Brazos',\n",
       " 'Cauca',\n",
       " 'Liao',\n",
       " 'Yalong',\n",
       " 'Iguaçu',\n",
       " 'Olyokma',\n",
       " 'Northern Dvina',\n",
       " 'Sukhona',\n",
       " 'Krishna',\n",
       " 'Iriri',\n",
       " 'Narmada',\n",
       " 'Lomami',\n",
       " 'Ottawa',\n",
       " 'Lerma',\n",
       " 'Rio Grande de Santiago',\n",
       " 'Elbe',\n",
       " 'Vltava',\n",
       " 'Zeya',\n",
       " 'Juruena',\n",
       " 'Upper Mississippi',\n",
       " 'Rhine',\n",
       " 'Athabasca',\n",
       " 'Canadian',\n",
       " 'North Saskatchewan',\n",
       " 'Vaal',\n",
       " 'Shire',\n",
       " 'Nen',\n",
       " 'Kızıl',\n",
       " 'Green',\n",
       " 'Milk',\n",
       " 'Chindwin',\n",
       " 'Sankuru',\n",
       " 'Wu',\n",
       " 'James',\n",
       " 'Kapuas',\n",
       " 'Desna',\n",
       " 'Helmand',\n",
       " 'Madre de Dios',\n",
       " 'Tietê',\n",
       " 'Vychegda',\n",
       " 'Sepik',\n",
       " 'Cimarron',\n",
       " 'Anadyr',\n",
       " 'Paraíba do Sul',\n",
       " 'Jialing River',\n",
       " 'Liard',\n",
       " 'Cumberland',\n",
       " 'White',\n",
       " 'Huallaga',\n",
       " 'Kwango',\n",
       " 'Draa',\n",
       " 'Gambia',\n",
       " 'Chenab',\n",
       " 'Yellowstone',\n",
       " 'Ghaghara',\n",
       " 'Huai',\n",
       " 'Aras',\n",
       " 'Seversky Donets',\n",
       " 'Bermejo',\n",
       " 'Fly',\n",
       " 'Guaviare',\n",
       " 'Kuskokwim',\n",
       " 'Tennessee',\n",
       " 'Vistula',\n",
       " 'Aruwimi',\n",
       " 'Daugava',\n",
       " 'Gila',\n",
       " 'Loire',\n",
       " 'Essequibo',\n",
       " 'Khoper',\n",
       " 'Tagus']"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "river_names"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Excellent! Now we can write a little random story generator:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I was floating down the Niagara in a boat with my friend the kangaroo.\n",
      "We came across a lonely-looking panda and said hello. THE END\n"
     ]
    }
   ],
   "source": [
    "my_river = random.choice(river_names)\n",
    "animal1 = random.choice(animals)\n",
    "animal2 = random.choice(animals)\n",
    "print(\"I was floating down the \" + my_river + \" in a boat with my friend the \" + animal1 + \".\")\n",
    "print(\"We came across a lonely-looking \" + animal2 + \" and said hello. THE END\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## JSON from elsewhere\n",
    "\n",
    "Another way to get data in JSON format is to request it directly from a web server. Many web sites make their data available in both HTML and JSON format. The HTML you fetch with a web browser; the JSON you can fetch with a computer program. (The JSON-formatted version of a web site's data is sometimes called a \"web API,\" where \"API\" stands for \"application programming interface\"—a version of the web site that you can access by writing computer programs.)\n",
    "\n",
    "There are a lot of [persnickety particulars](https://github.com/aparrish/dmep-python-intro/blob/master/web-requests.ipynb) about using web APIs, but the main gist is you need to (a) find an API that you want to work with; (b) learn how that API works, both in terms of how to structure the URLs when making requests, and how the data is structured in JSON; and (c) use Python to make the request to the desired URL.\n",
    "\n",
    "[This list of \"Awesome JSON Datasets\"](https://github.com/jdorfman/Awesome-JSON-Datasets) makes our lives a little bit easier, as it has links directly to URLs that we can try out. For example, the following URL can be used to access a web API that gives information on how many people are in space right now:\n",
    "\n",
    "    http://api.open-notify.org/astros.json\n",
    "    \n",
    "If you navigate to that page in your browser's navigation bar, you'll see the JSON data. (Sometimes browsers will add some pretty formatting or other features to this view, but the data actually returned from the server is just JSON.) Something like this:\n",
    "\n",
    "    {\"number\": 6, \"people\": [{\"craft\": \"ISS\", \"name\": \"Alexander Misurkin\"}, {\"craft\": \"ISS\", \"name\": \"Mark Vande Hei\"}, {\"craft\": \"ISS\", \"name\": \"Joe Acaba\"}, {\"craft\": \"ISS\", \"name\": \"Anton Shkaplerov\"}, {\"craft\": \"ISS\", \"name\": \"Scott Tingle\"}, {\"craft\": \"ISS\", \"name\": \"Norishige Kanai\"}], \"message\": \"success\"}\n",
    "    \n",
    "Of course, you could just save that file to disk and load it into your program the same way that we did with the Corpora Project files above. But if you wanted to make the request to grab the data *and* load it up in your program in one fell swoop, you can do that! You'll need to use the [`requests` library](http://docs.python-requests.org/en/master/) to do this. (This library is included with Anaconda by default, but you can also install it in other Python environments by typing `pip install requests`.)\n",
    "\n",
    "Fetching JSON from most web APIs is just two lines of code with `requests`. First, import the library:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import requests"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then call `requests.get(url).json()`, replacing `url` with the URL that you want to load. This expression will evaluate to the data from the JSON, already deserialized into a Python data structure. Handy!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = requests.get(\"http://api.open-notify.org/astros.json\").json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'message': 'success',\n",
       " 'number': 6,\n",
       " 'people': [{'craft': 'ISS', 'name': 'Alexander Misurkin'},\n",
       "  {'craft': 'ISS', 'name': 'Mark Vande Hei'},\n",
       "  {'craft': 'ISS', 'name': 'Joe Acaba'},\n",
       "  {'craft': 'ISS', 'name': 'Anton Shkaplerov'},\n",
       "  {'craft': 'ISS', 'name': 'Scott Tingle'},\n",
       "  {'craft': 'ISS', 'name': 'Norishige Kanai'}]}"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can write a tiny generative story about these fine spacepeople:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Alexander Misurkin is scolded and in space.\n",
      "Mark Vande Hei is open and in space.\n",
      "Joe Acaba is warmhearted and in space.\n",
      "Anton Shkaplerov is intense and in space.\n",
      "Scott Tingle is tactful and in space.\n",
      "Norishige Kanai is conventional and in space.\n"
     ]
    }
   ],
   "source": [
    "for item in data['people']:\n",
    "    print(item['name'] + \" is \" + random.choice(moods) + \" and in space.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nice!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
